package com.aistar.filter;

import com.aistar.pojo.Customer;
import com.aistar.service.CustomerService;
import com.aistar.service.MessageService;
import com.aistar.util.MessageUtil;
import com.aistar.util.RSAUtil;
import com.aistar.util.ServerResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.PrivateKey;


public class AutoLoginFilter implements Filter {
    private CustomerService customerService;
    private Log log = LogFactory.getLog(AutoLoginFilter.class);
    private MessageService messageService;


    public AutoLoginFilter(CustomerService customerService,
                           MessageService messageService) {
        this.customerService = customerService;
        this.messageService = messageService;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("自动登录过滤器加载成功");
    }

    @Override
    public void destroy() {
        log.info("自动登录过滤器销毁成功");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
        if (session.getAttribute("loginCustomer") == null) { // session里面没有数据
            if (cookies != null) { // cookie中有内容，解析cookie
                for (Cookie cookie : cookies) {
                    if ("autoLogin".equals(cookie.getName())) {
                        // cookie中有用户数据 解析cookie数据
                        int pos = cookie.getValue().indexOf("&");
                        Integer id = Integer.valueOf(cookie.getValue().substring(0, pos).trim());
                        String pwd = cookie.getValue().substring(pos + 1);
                        // 访问数据库查看是否数据
                        ServerResponse serverResponse = customerService.getById(id);
                        if (MessageUtil.STATUS_SUCCESS.equals(serverResponse.getStatus())) {
                            // 有数据，比对密码
                            PrivateKey privateKey = RSAUtil.getPrivateKey();
                            String passwordBlack = RSAUtil.decrypt(pwd, privateKey);
                            Customer customer = (Customer) serverResponse.getData();
                            String passwordCorrect = RSAUtil.decrypt(customer.getCustomerPassword(), privateKey);
                            if (passwordCorrect != null && passwordCorrect.equals(passwordBlack)) {
                                // 正确 存session 放行
                                session.setAttribute("loginCustomer", customer);
                                break;
                            }
                        }
                        // cookie数据异常
                        Cookie killCookie = new Cookie("autoLogin", null);
                        killCookie.setPath(request.getContextPath());
                        killCookie.setMaxAge(0); // 立即删除
                        response.addCookie(killCookie);
                        break;
                    }
                }
            }
        }
        if (session.getAttribute("loginCustomer") != null) {
            Customer customer = (Customer) request.getSession().getAttribute("loginCustomer");
            int count = (Integer) messageService.getUnreadCountByCustomerId(customer.getCustomerId()).getData();
            request.setAttribute("messageCount", count);
        }
        filterChain.doFilter(request, response);
    }
}
